import {useState, useRef, useEffect} from 'react';
import {Button, Form, Select, Row, Spin, Col} from 'antd';
import type {SelectProps} from 'antd';
import Dialog from "@/components/Dialog.tsx";
import {queryAllCusInfoList} from "@/axios/apis";

const SelectCustomer = ({onSure}) => {
    const [visible, setVisible] = useState(false)
    const [data, setData] = useState<SelectProps['options']>([]);
    const [keyword, setKeyword] = useState<string | undefined>(undefined);
    const [pagination, setPagination] = useState({
        pageNum: 1,          // 当前页码
        pageSize: 10,         // 每页条数
        hasMore: true         // 是否有更多数据
    });
    const [loading, setLoading] = useState(false); // 加载状态
    // 防抖搜索引用（避免频繁请求）
    const fetchData = (cusName: string, pageNum: number) => {
        setLoading(true)
        queryAllCusInfoList({
            pageNum: pageNum,
            pageSize: pagination.pageSize,
            cusName
        }).then(res => {
            if (+res.code === 200) {
                setPagination({
                    ...pagination,
                    pageNum: pageNum
                })
                if (!res.data.length) {
                    setPagination({
                        ...pagination,
                        hasMore: false
                    })
                }
                setData(list =>
                    pageNum === 1 ? res.data : [...list, ...res.data]
                );
            }
            setLoading(false)
        })
    }
    // 处理搜索输入变化
    const handleSearch = lodash.debounce((value: string) => {
        fetchData(value, 1)
    }, 300)
    // 处理下拉框滚动事件（滚动加载）
    const handlePopupScroll = lodash.debounce((e) => {
        if (!pagination.hasMore) return
        const {scrollTop, scrollHeight, clientHeight} = e.target;
        const isBottom = scrollHeight - scrollTop === clientHeight;
        if (isBottom && !loading && pagination.hasMore) {
            const nextPage = pagination.pageNum + 1;
            fetchData(keyword, nextPage);
        }
    }, 300)
    const onOk = () => {
        onSure(data?.find(item => keyword === item.id))
        setVisible(false)
        clear()
    }
    const clear = () => {
        setData([])
        setKeyword(undefined)
    }
    return (
        <>
            <Button type="primary" onClick={() => setVisible(true)}>选择已有客户</Button>
            <Dialog title="选择已有客户" visible={visible} setVisible={setVisible} width={666} onOk={onOk} clear={clear}>
                <Row>
                    <Col span={3}>
                        <div style={{lineHeight: 2}}>客户名称：</div>
                    </Col>
                    <Col span={21}>
                        <Select
                            value={keyword}
                            showSearch
                            placeholder="请输入关键词搜索"
                            filterOption={false}
                            onSearch={handleSearch}
                            onPopupScroll={handlePopupScroll}
                            style={{width: '100%'}}
                            loading={loading}
                            onChange={value => setKeyword(value as string)}
                        >
                            {data.map(item => (
                                <Option key={item.id} value={item.id}>
                                    {item.custName}
                                    <span style={{float: 'right'}}>{item.certiNo}</span>
                                </Option>
                            ))}

                            {loading && pagination.pageNum > 1 && (
                                <Option disabled>
                                    <div style={{textAlign: 'center'}}>
                                        <Spin size="small" />
                                    </div>
                                </Option>
                            )}

                            {!pagination.hasMore && pagination.pageNum > 1 && (
                                <Option disabled>
                                    <div style={{textAlign: 'center', color: '#999'}}>
                                        没有更多数据了
                                    </div>
                                </Option>
                            )}
                        </Select>
                    </Col>

                </Row>
            </Dialog>
        </>
    );
};

export default SelectCustomer;